package com.yungu.swift.api.base.handler;

import com.yungu.swift.api.base.Constants;
import com.yungu.swift.api.config.ApplicationConfig;
import com.yungu.swift.api.utils.RsaUtil;
import com.yungu.swift.assets.driver.service.DriverService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.SpringContextHolder;
import com.yungu.swift.constants.DriverConstant;
import com.yungu.swift.constants.MagicConstant;
import com.yungu.swift.utils.JsonUtils;
import com.yungu.swift.utils.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Objects;

import static com.yungu.swift.api.base.ApiErrorEnum.*;

/**
 * @author cuixiuyin
 * 司机处理器 —— 1. 校验司机信息 2. 将司机的 token 信息转化
 */
public class DriverTokenHandler extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        String token = request.getHeader(Constants.TOKEN_KEY);
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(Constants.TOKEN_KEY);
        }
        if (StringUtils.isBlank(token)) {
            outPrint(out, JsonUtils.writeJsonStr(ResponseData.buildErrorResponse(NOT_LOGIN.getCode(), NOT_LOGIN.getMsg())));
            return false;
        }
        DriverService driverService = SpringContextHolder.getBean(DriverService.class);
        Map<String, String> tokenResult = driverService.getDriverCachedByToken(token).getData();
        if (tokenResult == null) {
            ResponseData responseData = ResponseData.buildErrorResponse(LOGIN_EXPIRED.getCode(), LOGIN_EXPIRED.getMsg());
            outPrint(out, JsonUtils.writeJsonStr(responseData));
            return false;
        }
        if (StringUtils.isNull(tokenResult.get(MagicConstant.PARAMS_UUID))) {
            ResponseData responseData = ResponseData.buildErrorResponse(LOGIN_EXPIRED.getCode(), LOGIN_EXPIRED.getMsg());
            outPrint(out, JsonUtils.writeJsonStr(responseData));
            return false;
        }
        //司机状态判断
        if (StringUtils.isNotNull(tokenResult.get("status"))) {
            Integer status = Integer.parseInt(tokenResult.get("status"));
            if (!Objects.equals(status, DriverConstant.DRIVER_STATUS_NORMAL)) {
                ResponseData responseData = ResponseData.buildErrorResponse(USER_STATUS_ERROR.getCode(), USER_STATUS_ERROR.getMsg());
                outPrint(out, JsonUtils.writeJsonStr(responseData));
                return false;
            }
        }
        request.setAttribute("uuid", tokenResult.get("uuid"));
        response.reset();
        return true;
    }

    /**
     * 输出错误
     *
     * @param jsonstr
     */
    private void outPrint(PrintWriter out, String jsonstr) {
        if (ApplicationConfig.SERVER_CONFIG.getSafety().getEncrypt()) {
            out.print(RsaUtil.doUrlAndEncrypt(jsonstr));
        } else {
            out.print(jsonstr);
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {

    }
}
